package come.bowen.mypet;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

// V140: 记忆增强版 AI 服务
public class AIService {

    // 🔴 你的 Key (注意保管，不要发给别人)
    private static final String API_KEY = "sk-d7ae46dd07cf4881ae1aa084b707b632";
    private static final String API_URL = "https://api.deepseek.com/chat/completions";

    // 记忆文件路径
    private static final String MEMORY_FILE = "F:\\MyTablePet\\chat_memory.txt";

    private static List<String> history = new ArrayList<>();

    // --- 【优化点 1】记忆容量扩容 ---
    // 从 20 改为 60，相当于能记住最近 30 轮的对话
    private static final int MAX_HISTORY = 60;

    // --- 【优化点 2】字数安全阀 ---
    // 如果记忆总字数超过 6000 字，强制清理旧记忆，防止 API 报错
    private static final int MAX_TOTAL_CHARS = 6000;

    static {
        loadHistory();
    }

    public static void chat(String userMessage, AIResponseCallback callback) {
        new Thread(() -> {
            try {
                // 稍微丰富了一点人设
                String systemPrompt = "你是一个傲娇的二次元美少女桌宠。请用简短、可爱、稍微有点毒舌的语气回复我。不要超过30个字。如果我问你之前的对话，请根据上下文回答。";

                // --- 【优化点 3】更安全的 JSON 拼接方式 ---
                StringBuilder messagesJson = new StringBuilder();
                messagesJson.append("[");

                // 1. 先放入系统人设
                messagesJson.append("{\"role\": \"system\", \"content\": \"").append(escapeJson(systemPrompt)).append("\"}");

                // 2. 放入历史记忆 (如果有)
                for (String msg : history) {
                    messagesJson.append(",").append(msg);
                }

                // 3. 放入当前用户的话
                messagesJson.append(",{\"role\": \"user\", \"content\": \"").append(escapeJson(userMessage)).append("\"}");

                messagesJson.append("]");

                String jsonBody = "{"
                        + "\"model\": \"deepseek-chat\","
                        + "\"messages\": " + messagesJson.toString() + ","
                        + "\"stream\": false"
                        + "}";

                // 发送请求
                URL url = new URL(API_URL);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/json");
                conn.setRequestProperty("Authorization", "Bearer " + API_KEY);
                conn.setDoOutput(true);

                try (OutputStream os = conn.getOutputStream()) {
                    byte[] input = jsonBody.getBytes(StandardCharsets.UTF_8);
                    os.write(input, 0, input.length);
                }

                int status = conn.getResponseCode();
                InputStream stream = (status >= 200 && status < 300) ? conn.getInputStream() : conn.getErrorStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8));
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) response.append(line);

                String body = response.toString();

                if (status == 200) {
                    int contentIndex = body.indexOf("\"content\":");
                    if (contentIndex != -1) {
                        int start = body.indexOf("\"", contentIndex + 10) + 1;
                        int end = body.indexOf("\"", start);
                        while (body.charAt(end - 1) == '\\') {
                            end = body.indexOf("\"", end + 1);
                        }
                        String rawReply = body.substring(start, end);
                        String reply = unescapeJson(rawReply);

                        // 存入记忆
                        addHistory("user", userMessage);
                        addHistory("assistant", reply);
                        saveHistory();

                        callback.onSuccess(reply);
                    }
                } else {
                    System.out.println("API Error: " + body);
                    callback.onSuccess("呜...大脑好像过载了 (" + status + ")");
                }

            } catch (Exception e) {
                e.printStackTrace();
                callback.onSuccess("听不懂你在说什么！");
            }
        }).start();
    }

    private static void addHistory(String role, String content) {
        String jsonItem = "{\"role\": \"" + role + "\", \"content\": \"" + escapeJson(content) + "\"}";
        history.add(jsonItem);

        // 1. 检查条数限制
        while (history.size() > MAX_HISTORY) {
            history.remove(0); // 删掉最旧的
        }

        // 2. 检查字数限制 (智能清理)
        int currentTotalChars = 0;
        for (String h : history) {
            currentTotalChars += h.length();
        }
        // 如果字数太多，就疯狂删旧的，直到腾出空间
        while (currentTotalChars > MAX_TOTAL_CHARS && !history.isEmpty()) {
            String removed = history.remove(0);
            currentTotalChars -= removed.length();
        }
    }

    private static void saveHistory() {
        File file = new File(MEMORY_FILE);
        File parentDir = file.getParentFile();
        if (parentDir != null && !parentDir.exists()) {
            parentDir.mkdirs();
        }

        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
            for (String record : history) {
                writer.write(record);
                writer.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void loadHistory() {
        File file = new File(MEMORY_FILE);
        if (!file.exists()) return;

        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String line;
            while ((line = reader.readLine()) != null) {
                if (!line.trim().isEmpty()) {
                    history.add(line);
                }
            }
            System.out.println(">> 成功唤醒了 " + history.size() + " 条记忆！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static String escapeJson(String text) {
        return text.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n").replace("\r", "");
    }

    private static String unescapeJson(String text) {
        return text.replace("\\n", "\n").replace("\\\"", "\"").replace("\\\\", "\\");
    }

    public interface AIResponseCallback {
        void onSuccess(String reply);
    }
}